package com.lancoo.znbkxx.teacher.aibkTestCoach.questionToMark.adapter

import android.view.ViewGroup
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentManager
import androidx.fragment.app.FragmentPagerAdapter
import androidx.viewpager.widget.PagerAdapter

/**
 * 不做缓存，每次都会重新绘制的vpAdapter
 */
class MyVpFragmentPagerAdapter : FragmentPagerAdapter {
    private var fm: FragmentManager
    private var fragmentList: MutableList<Fragment>
    private var fragmentTitles: MutableList<String>? = null

    constructor(fm: FragmentManager, fragmentList: MutableList<Fragment>) : super(fm) {
        this.fm = fm
        this.fragmentList = fragmentList
    }

    constructor(fm: FragmentManager, fragmentList: MutableList<Fragment>, fragmentTitles: MutableList<String>?) : super(fm) {
        this.fm = fm
        this.fragmentList = fragmentList
        this.fragmentTitles = fragmentTitles
    }

    override fun getItem(position: Int): Fragment {
        return fragmentList[position]
    }

    override fun getCount(): Int {
        return fragmentList.size
    }

    override fun instantiateItem(container: ViewGroup, position: Int): Any {
        val fragment = super.instantiateItem(container, position) as Fragment
        fm.beginTransaction().show(fragment).commitAllowingStateLoss()
        return fragment
    }

    override fun destroyItem(container: ViewGroup, position: Int, `object`: Any) {
        val fragment: Fragment = fragmentList[position] // 获取要销毁的fragment
        fm.beginTransaction().hide(fragment).commitAllowingStateLoss()
    }

    override fun getPageTitle(position: Int): CharSequence? {
        return fragmentTitles!![position]
    }

    override fun getItemId(position: Int): Long {
        return fragmentList[position].hashCode().toLong()
    }

    override fun getItemPosition(`object`: Any): Int {
        return PagerAdapter.POSITION_NONE
    }
}